package com.study.config;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.study.intercept.MybatisInterceptor;

@Configuration
@MapperScan(basePackages = { "com.study.mapper.db3" }, sqlSessionTemplateRef = "db3SqlSessionTemplate")
public class DB3Config {

	@Autowired
	private MybatisInterceptor mybatisInterceptor;

	@Bean(name = "db3DataSource")
	public DataSource dataSourceCar(@Qualifier("db3Porperty") DruidXADataSource druidXADataSource) {
		AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
		xaDataSource.setXaDataSource(druidXADataSource);
		xaDataSource.setUniqueResourceName("db3DataSource");
		return xaDataSource;
	}

	@Bean(name = "db3SqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("db3DataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 扫描指定目录的xml
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mapping/db3/*Mapper.xml"));
		// 设置自定义mybatis拦截器
		bean.setPlugins(new Interceptor[] { mybatisInterceptor });
		return bean.getObject();
	}

	@Bean(name = "db3SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier("db3SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
